package com.vitabuybuy.tv.ui.home.live

import android.location.Location
import android.os.Bundle
import android.view.View
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.android.material.tabs.TabLayout
import com.google.gson.reflect.TypeToken
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.ext.mmkv
import com.library.common.util.JsonUtil
import com.library.common.util.MMKVContancts
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityLiveZoneBinding
import com.vitabuybuy.tv.dto.FirstCategoryDto
import com.vitabuybuy.tv.dto.LiveListDto
import com.vitabuybuy.tv.dto.RegionDto
import com.vitabuybuy.tv.dto.TabEntity
import com.vitabuybuy.tv.ui.auth.LoginActivity
import com.vitabuybuy.tv.ui.home.group.SearchGroupBuyOrBiddingOrLiveActivity
import com.vitabuybuy.tv.ui.home.live.viewmodel.LiveAreaViewModel
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.RoomInfo
import com.vitabuybuy.tv.ui.tencent.liveroom.ui.AudienceLiveRoomActivity
import com.vitabuybuy.tv.utils.GetAddressUtil
import com.vitabuybuy.tv.utils.LocationUtil
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import kotlinx.android.synthetic.main.activity_live_zone.*
import java.util.*

/**
 * 作者：SimGa
 * 日期：2020/12/19
 * 时间：14:56
 * 包名：com.vitabuybuy.tv.ui.home.live
 */
class LiveZoneActivity : BaseActivity<LiveAreaViewModel, ActivityLiveZoneBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_live_zone

    private val mTabEntities = ArrayList<CustomTabEntity>()

    private var categoryId = -1
    private var pageNumber = 1
    private var regionId = -1
    private var desc = "viewer_quantity"//排序数值（最热（viewer_quantity），最新（create_time））
    private var areaDialog: BottomDialog? = null

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.live_list))
        mIvRight.apply {
            setImageResource(R.drawable.icon_navbar_sousuo_black)
            visibility = View.VISIBLE
            setOnClickListener {
                SearchGroupBuyOrBiddingOrLiveActivity.openActivity(
                    mContext,
                    SearchGroupBuyOrBiddingOrLiveActivity.FROM_LIVE
                )
            }
        }
        mBinding.mViewModel = viewModel
        mTabEntities.add(TabEntity(getString(R.string.hottest), 0, 0))
        mTabEntities.add(TabEntity(getString(R.string.latest), 0, 0))
        mTabLayout_1.setTabData(mTabEntities)
        LocationUtil.getCurrentLocation(mContext, object : LocationUtil.LocationCallBack {
            override fun onSuccess(location: Location) {
                val address = GetAddressUtil(mContext).getAddress(
                    location.longitude,
                    location.latitude
                )
                if (!address.isNullOrEmpty()) {
                    val address = address[0]
                    tv_loaction.text = address.countryName
                }
            }

            override fun onFail(msg: String) {
            }
        })
    }

    override fun observeData() {
        val categoryList = JsonUtil.fromJson(
            mmkv.decodeString(MMKVContancts.CATEGORY_LIST, ""),
            object : TypeToken<ArrayList<FirstCategoryDto>>() {}.type
        ) as ArrayList<FirstCategoryDto>
        tlClassification.apply {
            removeAllTabs()
            addTab(
                tlClassification.newTab().setText(getString(R.string.recommend))
                    .setTag(categoryId)
            )
            for (str in categoryList) {
                addTab(tlClassification.newTab().setText(str.name).setTag(str.id))
            }
            viewModel.getLiveList(categoryId, desc, regionId, null, pageNumber)
        }
    }

    override fun eventHandling() {
        tlClassification.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(p0: TabLayout.Tab?) {
            }

            override fun onTabUnselected(p0: TabLayout.Tab?) {
            }

            override fun onTabSelected(p0: TabLayout.Tab?) {
                categoryId = p0?.tag as Int
                pageNumber = 1
                viewModel.getLiveList(categoryId, desc, regionId, null, pageNumber)
            }
        })
        mTabLayout_1.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                when (position) {
                    0 -> {
                        desc = "viewer_quantity"
                    }
                    1 -> {
                        desc = "create_time"
                    }
                }
                pageNumber = 1
                viewModel.getLiveList(categoryId, desc, regionId, null, pageNumber)
            }

            override fun onTabReselect(position: Int) {
                areaDialog = BottomDialog(mContext, 5)
                viewModel.getRegionList(null)
            }
        })
        refresh.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber++
                viewModel.getLiveList(categoryId, desc, regionId, null, pageNumber)
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                pageNumber = 1
                viewModel.getLiveList(categoryId, desc, regionId, null, pageNumber)
            }
        })
        tv_loaction.setOnClickListener {
            areaDialog = BottomDialog(mContext, 5)
            viewModel.getRegionList(null)
        }
    }


    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            0 -> {
                viewModel.getLiveList(categoryId, desc, regionId, null, pageNumber)
            }
            1 -> {
                refresh.onLoad(msg.arg1)
            }
            2 -> {
                if (!mmkv.decodeBool(MMKVContancts.IS_LOGIN_IN, false)) {
                    LoginActivity.openActivity(mContext)
                    return
                }
                val item = msg.obj as LiveListDto
                val roomInfo = RoomInfo().apply {
                    audienceCount = item.viewerQuantity
                    roomID = item.roomNumber
                    roomInfo = item.title
                    roomName = item.title
                    mixedPlayURL = item.playUrl
                    item.store?.let {
                        roomCreator = it.id.toString()
                        authorName = it.name
                        authorId = it.id.toString()
                        authorAvatar = it.logo
                        isExecutor = false
                    } ?: let {
                        item.executor?.let {
                            roomCreator = it.id.toString()
                            authorName = it.realname
                            authorId = it.id.toString()
                            authorAvatar = it.avatar
                            isExecutor = true
                        }
                    }
                    authorRegion = item.allRegion
                    liveId = item.id
                    attention = item.isAttention
                    userId = mmkv.decodeInt(MMKVContancts.USER_ID).toString()
                    userName = mmkv.decodeString(MMKVContancts.USER_NICKNAME)
                    createRoom = false
                }
                AudienceLiveRoomActivity.openActivity(mContext, roomInfo)
            }
            3 -> {
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                            selectAbles?.run {
                                var area = ""
                                for (selectAble in this) {
                                    area = selectAble.name
                                    regionId = selectAble.id
                                }
                                areaDialog = null
                                mBinding.tvLoaction.text = area
                                pageNumber = 1
                                viewModel.getLiveList(categoryId, desc, regionId, null, pageNumber)
                            }
                        }

                        override fun onClickOnEach(selectAble: RegionDto?) {
                            viewModel.getRegionList(selectAble?.id)
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(null, LiveZoneActivity::class.java)
        }
    }
}